package com.ilvyou.api.common;

import com.ilvyou.api.bean.result.Result;
import com.ilvyou.core.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by GuanYuCai on 2016/9/6 0006.
 */
public class ExceptionResolver extends SimpleMappingExceptionResolver {
    private Logger log = Logger.getLogger(ExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        try {
            Result r = new Result();
            r.setCode(Constant.ERR);
            r.setMessage("网络异常");

            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control","no-cache, must-revalidate");
            response.getWriter().write(StringUtil.toJson(r));

            ex.printStackTrace();
            log.error("Error! ", ex);

            ModelAndView mv = new ModelAndView();
            mv.setStatus(HttpStatus.OK);
            return mv;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
